(function($) {

    /**
     * 调整样式
     * @param selectObj
     */
    function _1(selectObj) {
        var _3 = $.data(selectObj, "combobox").options;
        var combobox = $.data(selectObj, "combobox").combobox;
        var content = $.data(selectObj, "combobox").content;
        //如果select的宽度为auto，则默认设置为110
        if (isNaN(_3.width)) {
//            _3.width = combobox.find("input.combobox-text").outerWidth();
            _3.width = 110;
        }
        var outerWidth = combobox.find(".combobox-arrow").outerWidth();
        var _7 = _3.width - outerWidth - (combobox.outerWidth() - combobox.width());
        combobox.find("input.combobox-text").width(_7);
        if (_3.listWidth) {
            content.width(_3.listWidth);
        } else {
//            content.width($.boxModel == true ? combobox.outerWidth() - (content.outerWidth() - content.width()) : combobox.outerWidth());
            //_7再加上图片的宽度(18)再加上2做调整
            content.width(_7 + 18 + 2);
        }
        if (_3.listHeight) {
            content.height(_3.listHeight);
        }
    };

    /**
     * 仿造一个select
     * @param selectObj
     */
    function createSelect(selectObj) {
        //隐藏原生的select
        $(selectObj).hide();

        //构建新的仿select控件
        var newSpan = $("<span class=\"combobox\"></span>").insertAfter(selectObj);
        $("<input type=\"hidden\" class=\"combobox-value\" />").appendTo(newSpan);
        var newText = $("<input type=\"text\" class=\"combobox-text\" />").appendTo(newSpan);
        $("<span><span class=\"combobox-arrow\"></span></span>").appendTo(newSpan);
        var newDiv = $("<div class=\"combobox-content\"></div>").appendTo('body');
        newDiv.attr('id', 'combobox-content-'+$(selectObj).parent().attr('id'));
        var selectName = $(selectObj).attr("name");
        if (selectName) {
            newSpan.find("input.combobox-value").attr("name", selectName);
            $(selectObj).removeAttr("name").attr("comboboxName", selectName);
        }
        newText.attr("autocomplete", "off");
        return {combobox:newSpan,content:newDiv};
    };

    /**
     * 绑定事件
     * @param selectObj
     */
    function _e(selectObj) {
        var _10 = $.data(selectObj, "combobox").options;
        var combobox = $.data(selectObj, "combobox").combobox;
        var content = $.data(selectObj, "combobox").content;
        var _13 = combobox.find(".combobox-text");
        var _14 = combobox.find(".combobox-arrow");
        $(document).unbind(".combobox");
        content.unbind(".combobox");
        _13.unbind(".combobox");
        _14.unbind(".combobox");
        if (!_10.disabled) {
            $(document).bind("mousedown.combobox", function() {
                $(".combobox-content").hide();
            });
            content.bind("mousedown.combobox", function() {
                return false;
            });
            _13.bind("focus.combobox", function() {
                _3d(selectObj, "");
            });
//                    .bind("keyup.combobox", function(e) {
//                var _15 = content.find("div.combobox-item-selected");
//                switch (e.keyCode) {
//                    case 38:
//                        var _16 = _15.prev();
//                        if (_16.length) {
//                            _15.removeClass("combobox-item-selected");
//                            _16.addClass("combobox-item-selected");
//                        }
//                        break;
//                    case 40:
//                        var _17 = _15.next();
//                        if (_17.length) {
//                            _15.removeClass("combobox-item-selected");
//                            _17.addClass("combobox-item-selected");
//                        }
//                        break;
//                    case 13:
//                        _18(selectObj, _15.attr("value"));
//                        content.hide();
//                            e.stopPropagation();
//                        break;
//                    case 27:
//                        content.hide();
//                        break;
//                    default:
//                        _3d(selectObj, $(this).val());
//                }
//                return false;
//            });
            _14.bind("click.combobox", function() {
                _13.focus();
            }).bind("mouseenter.combobox", function() {
                $(this).addClass("combobox-arrow-hover");
            }).bind("mouseleave.combobox", function() {
                $(this).removeClass("combobox-arrow-hover");
            });
        }
    }

    ;
    function _18(_19, _1a) {
        var _1b = $.data(_19, "combobox").data;
        var _1c = $.data(_19, "combobox").options;
        var _1d = $.data(_19, "combobox").combobox;
        var _1e = $.data(_19, "combobox").content;
        _1e.find("div.combobox-item-selected").removeClass("combobox-item-selected");
        for (var i = 0; i < _1b.length; i++) {
            var rec = _1b[i];
            if (rec[_1c.valueField] == _1a) {
                var _1f = _1d.find("input.combobox-value").val();
                _1d.find("input.combobox-value").val(rec[_1c.valueField]);
                _1d.find("input.combobox-text").val(rec[_1c.textField]);
                _1e.find("div.combobox-item[value=" + _1a + "]").addClass("combobox-item-selected");
                _1c.onSelect.call(_19, rec);
                if (_1f != _1a) {
                    if (window[_1c.onChange]) {
                        window[_1c.onChange].call(_19, _1a, _1f);
                    }
                }
                _20(_19, true);
                return;
            }
        }
    };

    function _21(selectObj, selectedOption) {
        var combobox = $.data(selectObj, "combobox").combobox;
        var _25 = $.data(selectObj, "combobox").options;
        var data = $.data(selectObj, "combobox").data;
        var optionValue,optionText;
        var inputValue = combobox.find("input.combobox-value").val();
        if (typeof selectedOption == "object") {
            optionValue = selectedOption[_25.valueField];
            optionText = selectedOption[_25.textField];
        } else {
            optionValue = selectedOption;
            for (var i = 0; i < data.length; i++) {
                if (data[i][_25.valueField] == optionValue) {
                    optionText = data[i][_25.textField];
                    break;
                }
            }
        }
        combobox.find("input.combobox-value").val(optionValue);
        combobox.find("input.combobox-text").val(optionText);
        _20(selectObj, true);
//        if (inputValue != optionValue) {
//            window[_25.onChange].call(selectObj, optionValue, inputValue);
//        }
    }

    ;
    function _2a(_2b) {
        var _2c = $.data(_2b, "combobox").combobox;
        return _2c.find("input.combobox-value").val();
    };

    /**
     * 创建option部分
     * @param selectObj
     */
    function createOptions(selectObj) {
        var options = $.data(selectObj, "combobox").options;
        var optionArr = [];
        $(">option", selectObj).each(function() {
            var optionObj = {};
            optionObj[options.valueField] = $(this).attr("value");// || $(this).html();
            optionObj[options.textField] = $(this).html();
            optionObj["selected"] = $(this).attr("selected");
            optionArr.push(optionObj);
        });
        return optionArr;
    };

    /**
     * 把option部分追加到select上面
     * @param selectObj
     * @param optionArr
     */
    function addOptionToSelect(selectObj, optionArr) {
        $.data(selectObj, "combobox").data = optionArr;
        var _35 = $.data(selectObj, "combobox").options;
        var content = $.data(selectObj, "combobox").content;
        var selectedOption = null;
        content.empty();
        for (var i = 0; i < optionArr.length; i++) {
            var _38 = $("<div class=\"combobox-item\"></div>").appendTo(content);
            _38.attr("value", optionArr[i][_35.valueField]);
            _38.html(optionArr[i][_35.textField]);
            if (optionArr[i]["selected"]) {
                selectedOption = optionArr[i];
            }
        }
        if (selectedOption) {
            _21(selectObj, selectedOption);
        }
        $(".combobox-item", content).hover(function() {
            $(this).addClass("combobox-item-hover");
        }, function() {
            $(this).removeClass("combobox-item-hover");
        }).click(function() {
            content.hide();
            _18(selectObj, $(this).attr("value"));
        });
    };

    /**
     * 根据url取值，需要废除
     * @param selectObj
     * @param url
     */
    function _39(selectObj, url) {
        var _3b = $.data(selectObj, "combobox").options;
        if (url) {
            _3b.url = url;
        }
        if (!_3b.url) {
            return;
        }
        $.ajax({url:_3b.url,dataType:"json",success:function(_3c) {
            addOptionToSelect(selectObj, _3c);
            _3b.onLoadSuccess.apply(this, arguments);
        },error:function() {
            _3b.onLoadError.apply(this, arguments);
        }});
    };

    /**
     * 高亮显示与输入值相匹配的项
     * @param selectObj
     * @param inputV
     */
    function _3d(selectObj, inputV) {
        inputV = inputV || "";
        var _40 = $.data(selectObj, "combobox").combobox;
        var _41 = $.data(selectObj, "combobox").content;
        var _42 = _40.find("input.combobox-text").val();
        _41.find("div.combobox-item-selected").removeClass("combobox-item-selected");
        _41.find("div.combobox-item").each(function() {
            var _43 = $(this);
            if (_43.text().indexOf(inputV) == 0) {
                _43.show();
                if (_43.text() == _42) {
                    _43.addClass("combobox-item-selected");
                }
            } else {
                _43.hide();
                _40.find("input.combobox-value").val('selfInput');

            }
        });
        _41.css({display:"block",left:_40.offset().left,top:_40.offset().top + _40.outerHeight()});
        if ($.fn.window) {
            _41.css("z-index", $.fn.window.defaults.zIndex++);
        }
        if (_41.find("div.combobox-item-selected").length == 0) {
            _41.find("div.combobox-item:visible:first").addClass("combobox-item-selected");
        }
    };

    /**
     * 验证用
     * @param selectObj
     * @param _45
     */
    function _20(selectObj, _45) {
//        if ($.fn.validatebox) {
//            var _46 = $.data(selectObj, "combobox").options;
//            var _47 = $.data(selectObj, "combobox").combobox.find("input.combobox-text");
//            _47.validatebox(_46);
//            if (_45) {
//                _47.validatebox("validate");
//            }
//            var $sel = $(selectObj);
//            var $comboDiv = $sel.parent();
//            var $combovalue = $comboDiv.find(".combobox-value");
//            var $combotext = $comboDiv.find(".combobox-text");
//
//            var pattern = /\W+/;
//            var rules = $sel.attr("validator").split(pattern);
//            var flg = true;
//
//            for (i = 0; i < rules.length; i++) {
//                switch (rules[i]) {
//                    case "required":
//                        if ($combovalue.val() == "") {
//                            flg = false;
//                            $combotext.addClass("validatebox-invalid");
////                            addTip($combotext[0], allRules[rules[i]].alertText);
//
//                        }
//                        break;
//                }
//            }
//            if (flg) {
//                $combotext.removeClass("validatebox-invalid");
//            }
//        }
    };

    /**
     * 设定是不是只读的
     * @param selectObj
     * @param disable
     */
    function _48(selectObj, disable) {
        var _4b = $.data(selectObj, "combobox").options;
        var combobox = $.data(selectObj, "combobox").combobox;
        if (disable) {
            _4b.disabled = true;
            $(selectObj).attr("disabled", true);
            combobox.find(".combobox-value").attr("disabled", true);
            combobox.find(".combobox-text").attr("disabled", true);
        } else {
            _4b.disabled = false;
            $(selectObj).removeAttr("disabled");
            combobox.find(".combobox-value").removeAttr("disabled");
            combobox.find(".combobox-text").removeAttr("disabled");
        }
    };

    /**
     * 相当于构造函数
     * @param config
     * @param _4e
     */
    $.fn.combobox = function(config, _4e) {
        if (typeof config == "string") {
            switch (config) {
                case "select":
                    return this.each(function() {
                        _18(this, _4e);
                    });
                case "setValue":
                    return this.each(function() {
                        _21(this, _4e);
                    });
                case "getValue":
                    return _2a(this[0]);
                case "reload":
                    return this.each(function() {
                        _39(this, _4e);
                    });
                case "disable":
                    return this.each(function() {
                        _48(this, true);
                        _e(this);
                    });
                case "enable":
                    return this.each(function() {
                        _48(this, false);
                        _e(this);
                    });
            }
        }
        config = config || {};
        return this.each(function() {
            var comboboxConf = $.data(this, "combobox");
            if (comboboxConf) {
                $.extend(comboboxConf.options, config);
            } else {
                //创建新的仿select组件
                var r = createSelect(this);
                var t = $(this);
                t.attr("diabled");
                comboboxConf = $.data(this, "combobox", {options:$.extend({}, $.fn.combobox.defaults, {width:(parseInt(t.css("width")) || undefined),listWidth:t.attr("listWidth"),listHeight:t.attr("listHeight"),valueField:t.attr("valueField"),textField:t.attr("textField"),editable:(t.attr("editable") ? t.attr("editable") == "true" : undefined),disabled:(t.attr("disabled") ? true : undefined),url:t.attr("url"),required:(t.attr("required") ? (t.attr("required") == "true" || t.attr("required") == true) : undefined),missingMessage:(t.attr("missingMessage") || undefined)}, config),combobox:r.combobox,content:r.content});
                t.removeAttr("disabled");
                addOptionToSelect(this, createOptions(this));
            }
            $("input.combobox-text", comboboxConf.combobox).attr("readonly", !comboboxConf.options.editable);
//            _39(this);
            _48(this, comboboxConf.options.disabled);

            //添加事件
            _e(this);
            _1(this);
            _20(this);

            var $forms = jQuery('body form');
            var $vf = null;

            $forms.each(function() {
                if ($(this).find("input[class=combobox-text]").length != 0) {
                    $vf = $(this);
                    return false;
                }
            })

            if ($vf && $vf.attr("isImValidation") == "true") {
                $(this).validatebox();
            }

        });
    };
    $.fn.combobox.defaults = {width:"auto",listWidth:null,listHeight:null,valueField:"value",textField:"text",editable:true,disabled:false,url:null,required:false,missingMessage:"This field is required.",onLoadSuccess:function() {
    },onLoadError:function() {
    },onSelect:function(_50) {
    },onChange:function(_51, _52) {
    }};
})(jQuery);